package com.ce.server.controller;

import com.ce.server.common.AdminLoginParam;
import com.ce.server.common.RespBean;
import com.ce.server.pojo.Admin;
import com.ce.server.pojo.Student;
import com.ce.server.service.IAdminService;
import com.ce.server.service.IStudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @DATE: 2021/11/14 16:12
 * @Author: 小爽帅到拖网速
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {
  @Autowired
  private IAdminService adminService;

  @Autowired
  private IStudentService studentService;

  @Value("${type.admin}")
  private String admin_type;
  @Value("${type.student}")
  private String student_type;

  @ApiOperation(value = "登录之后向前端返回token")
  @PostMapping("/login")
  public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
    return adminService.login(adminLoginParam.getAccount_no(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
  }

  @ApiOperation(value = "获取当前登录用户信息")
  @GetMapping("/admin/info")
  public UserDetails getAdminInfo(Principal principal){
    if (principal==null){
      return null;
    }

    String no = principal.getName();
    if (StringUtils.startsWithIgnoreCase(no,admin_type)){
      Admin admin = adminService.getAdminByWno(no);
      // 敏感信息不返回
      admin.setPassword(null);
      admin.setRoles(adminService.getRoles(admin.getWno()));
      return admin;
    }else{
      Student student = studentService.getStudentBySno(no);
      student.setPass(null);
      student.setRoles(studentService.getRoleBySno(student.getSno()));
      return student;
    }

  }

  @ApiOperation(value = "前端退出登录，后端返回状态码")
  @PostMapping("/logout")
  public RespBean logout(){
    // 将当前springsecurity登录置空
    SecurityContextHolder.getContext().setAuthentication(null);
    return RespBean.success("注销成功！");
  }


}
